package com.code.bolg.controller;

import com.code.bolg.bean.Article;
import com.code.bolg.bean.Category;
import com.code.bolg.enums.DelFlagEnum;
import com.code.bolg.output.ArticleOutPut;
import com.code.bolg.output.CategoryOutPut;
import com.code.bolg.output.IndexDto;
import com.code.bolg.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Category
 *
 * @author  2018-10-12
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增或编辑
     */
    @PostMapping("/saveOrUpdate")
    public Object save(Category category) {
        category.setFlag(DelFlagEnum.NOTDELETE.getCode());
        if(category.getCategoryId()!=null){
            category.setUpdateDate(new Date());
        }else if(category.getCategoryId()==null){
            category.setCreatDate(new Date());
            category.setUpdateDate(category.getCreatDate());
        }
        Category save = categoryService.save(category);
        CategoryOutPut outPut = new CategoryOutPut();
        BeanUtils.copyProperties(save,outPut);
        return outPut;
    }

    /**
     * 删除
     */
    @GetMapping("/delete")
    public Object delete(int id) {
        return categoryService.deleteById(id);
    }

    /**
     * 查询
     */
    @GetMapping("/find")
    public Object find(int id) {
        Category category = categoryService.findById(id);
        return category;
    }

    /**
     *  查询
     */
    @PostMapping("/list")
    public Object list( ) {
        List<CategoryOutPut> list = new ArrayList<>();
        List<Category> all = categoryService.findAll( );
        /*for (Category c:all){
            CategoryOutPut ouput = new CategoryOutPut();
            BeanUtils.copyProperties(c,ouput);
            list.add(ouput);
        }*/

        all.stream().forEach(model -> {
            CategoryOutPut ouput = new CategoryOutPut();
            BeanUtils.copyProperties(model,ouput);
            list.add(ouput);
        });

        IndexDto<CategoryOutPut> index = new IndexDto<>();
        index.setList(list);
        index.setCount(list.size());

        return index;
    }

}

